import {
	$http
} from '@/utils/index.js'
import store from '../store/store'

// 配置请求根路径
let envVersion = wx.getAccountInfoSync().miniProgram.envVersion;

switch (envVersion) {
	case "develop": // 开发版
		// $http.baseUrl = "http://192.168.8.48:9001"; //开发环境(json)
		// $http.baseUrl = "https://h4j2bb2b9dd1.ngrok.xiaomiqiu123.top"
		// $http.baseUrl = "http://192.168.8.66:9001"; //开发环境(Van)
		$http.baseUrl = "http://47.108.199.203:9001"; //测试环境
		// $http.baseUrl = "https://www.bozhonghl.com:9000";
		break;
	case "trial": // 体验版
		$http.baseUrl = "http://47.108.199.203:9001"; //测试环境
		// $http.baseUrl = "https://www.bozhonghl.com:9000";
		break;
	case "release": // 正式版
		$http.baseUrl = "https://www.bozhonghl.com:9000";
		break;
}

// 请求开始之前
$http.beforeRequest = async function(options) {
	uni.showLoading({
		title: '数据加载中...',
	})
	if (options.url.split(options.baseUrl)[1] == '/api/commodityInfo/queryDetailByCommodityId') {
		options.header.activityCode = uni.getStorageSync('activityCode')
	}
	if (store.state.user.ylProjectCode) {
		options.header.projectCode = store.state.user.ylProjectCode
		options.header.enterpriseCode = store.state.user.ylEnterprise.enterpriseCode
	}
	if (store.state.user.ylToken) {
		options.header.Authorization = store.state.user.ylToken
	}
}

// 请求完成之后
$http.afterRequest = function(res, resolve, reject) {
	if (res.statusCode === 200) {
		if (res.data.status === 200) {
			uni.getStorageSync('activityCode') ? uni.removeStorageSync('activityCode') : ''
			uni.hideLoading()
			resolve(res)
		} else {
			if (res.header['Content-Type'] == "image/png; charset=UTF-8") {
				uni.hideLoading()
				return resolve(res)
			}
			if (res.data.status === 401) {
				uni.$showMsg('用户未登录，请先登录')
				// uni.navigateTo({
				// 	url: '/subPackages/login/login'
				// })
				// return uni.showModal({
				// 	content: "还未登录，请先登录",
				// 	success(res) {
				// 		if (res.confirm) {
				// 			uni.navigateTo({
				// 				url: '/subPackages/login/login'
				// 			})
				// 		} else {
				// 			uni.navigateBack()
				// 		}
				// 	},
				// })
				return setTimeout(()=>{
					uni.navigateBack()
				},1500)
			}
			uni.hideLoading()
			uni.$showMsg(res.data.message)
			reject(res)
		}
	} else {
		uni.hideLoading()
		uni.$showMsg(res.data.message)
		reject(res)
	}
}

// 将$http挂载到uni全局对象
uni.$http = $http
// 封装的展示消息提示的方法
uni.$showMsg = function(title = '数据加载失败！', icon = 'none', duration = 2000) {
	uni.showToast({
		title,
		duration,
		icon,
	})
}